#!/bin/bash
# This script starts a Samba AD domain controller
# based on this manual: http://wiki.rosalab.ru/ru/index.php/Samba
set -efu

for i in samba smb nmb winbind
do
	if systemctl -q is-active "$i"; then
		systemctl stop "$i"
	fi
done

mv /etc/samba/smb.conf /etc/samba/smb.conf.old
mv /etc/krb5.conf /etc/krb5.conf.old

smbd -b | grep -E "LOCKDIR|STATEDIR|CACHEDIR|PRIVATE_DIR" | awk '{print $NF}' | xargs -I'{}' rm -fv '{}'/*.{tdb,ldb} || :

ip="$(hostname -I | tr ' ' '\n' | head -n 1)"
echo "$ip $(hostname) $(hostname --short)" >> /etc/hosts

samba-tool domain provision \
	--adminpass=SambaAdmin2022 \
	--krbtgtpass=SambaKrbgt022 \
	--dnspass=SambaDns2022 \
	--dns-backend="$DNSTYPE" \
	--domain="$(hostname --domain | awk -F '.' '{print $1}' | tr '[:lower:]' '[:upper:]')" \
	--realm="$(hostname --domain | tr '[:lower:]' '[:upper:]')" \
	--use-rfc2307

cp /var/lib/samba/private/krb5.conf /etc/krb5.conf

if [ "$DNSTYPE" = "BIND9_DLZ" ]; then
	echo 'include "/var/lib/samba/bind-dns/named.conf";' >> /etc/named.conf
fi

systemctl enable --now samba
sleep 2
systemctl -q is-active samba

if [ "$DNSTYPE" = "BIND9_DLZ" ]; then
	systemctl enable --now named
	sleep 2
	systemctl -q is-active named
fi
